import cv2
import time,PIL,os
from PIL import ImageGrab
import numpy as np
import time
from tempfile import NamedTemporaryFile
import cv2
from pprint import pprint
from concurrent.futures import ThreadPoolExecutor
import sys
 
dataDir = "D:/argostranslate/data"
cacheDir = "D:/argostranslate/cache"
os.environ["XDG_DATA_HOME"] = dataDir
os.environ["XDG_CACHE_HOME"] = cacheDir
import argostranslate.package
import argostranslate.translate
#截图
class ScreenCut:
    def __init__(self):
        if not os.path.exists("E:/ningyuan/sumimoto/Curelasto/tmp/"):
            os.makedirs("E:/ningyuan/sumimoto/Curelasto/tmp/")
        try:
            os.remove("E:/ningyuan/sumimoto/Curelasto/tmp/scr.png")
            os.remove("E:/ningyuan/sumimoto/Curelasto/tmp/cut.png")
        except:pass
        self.scrImg = open("E:/ningyuan/sumimoto/Curelasto/tmp/scr.png","wb+")
        self.cutImg = open("E:/ningyuan/sumimoto/Curelasto/tmp/cut.png","wb+")
    def cut(self):
        self.scrren_cut()
        #print("截图完成")
    def scrren_cut(self):
        # 获取传递给Python脚本的参数
        arg1 = sys.argv[1]
        arg2 = sys.argv[2]
        x = int(arg1)  # 将第一个参数转换为整数
        y = int(arg2)  # 将第二个参数转换为整数
        #print("x is:", x)
        #print("y is:", y)
         # 截取固定区域 (500,500) 到 (600,600)
        # img = ImageGrab.grab(bbox=(
        #         1000,       # 起始x坐标
        #         600,       # 起始y坐标
        #         1000+800,  # 起始x + 宽度
        #         600+400   # 起始y + 高度
        #     ))
        img = ImageGrab.grab(bbox=(
            x,       # 起始x坐标
            y,       # 起始y坐标
            x+500,  # 起始x + 宽度
            y+200   # 起始y + 高度
        ))
        img.save(self.cutImg.name)
    
class OCR:
    def __init__(self,imagePath,instPack=None,**kwargs):
        from paddleocr import PaddleOCR
        # 路径可替换为你的项目文件夹或随便一个专门装PaddleOCR模型的文件夹路径
        self.paddleocr = PaddleOCR(
                                    lang='ch', # 指定中文语言
                                    use_angle_cls=False, # 中文通常不需要角度分类
                                    **kwargs  # 统一通过关键字参数传递额外参数
                                    )
        self.imagePath = imagePath
        self.instPack = instPack  # 明确接收参数
    def ocr(self,**kwargs):
        result = self.paddleocr.ocr(self.imagePath,**kwargs)[0]
        if not result:
            return None
        rd = list(map(lambda i:{"block":{
                                         "topleft":(i[0][0][0],i[0][0][1]),
                                         "topright":(i[0][1][0], i[0][1][1]),
                                         "bottomleft":(i[0][2][0], i[0][2][1]),
                                         "bottomright":(i[0][3][0], i[0][3][1])
                                         },
                                "text":i[1][0],
                                "confidence":i[1][1]},
                      result))
        
        return rd
 
class Translate:
    def __init__(self,
                 fromLang = "en",
                 toLang = "zh",
                 instPack = True):
        if not (os.path.exists(dataDir) and os.path.exists(cacheDir)):
            raise FileNotFoundError("dataDir or cacheDir is not exists")
        if instPack:
            argostranslate.package.update_package_index()
            available_packages = argostranslate.package.get_available_packages()
            package_to_install = next(filter(lambda x: x.from_code == from_code and x.to_code == to_code, available_packages))
            argostranslate.package.install_from_path(package_to_install.download())
        self.fromLang = fromLang
        self.toLang = toLang
    def translate(self,text):
        return argostranslate.translate.translate(text,self.fromLang,self.toLang)
cut = ScreenCut()
#print("Init done.")
 
cut.cut()
#print("cut done.")

#ocr = OCR("E:/ningyuan/sumimoto/Curelasto/tmp/cut.png")
ocr = OCR(
    imagePath="E:/ningyuan/sumimoto/Curelasto/tmp/cut.png",
    instPack='123456789'  # 确保只在此处传递一次
)

if not os.path.exists("E:/ningyuan/sumimoto/Curelasto/tmp/cut.png"):
    #print("已取消截图")
    exit()
result = ocr.ocr()


# 用于存储提取的文本
extracted_text = ''
for line in result:
    extracted_text += line['text']

if not result:
    #print("未识别到文字")
    print("Text not recognized")
    exit()
print("ocr-result:",extracted_text)